package cn.edu.zjicm.wordsnet_d.activity;

import java.util.Date;
import java.util.List;
import java.util.Vector;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.BroadcastReceiver.HomeKeyEventBroadCastReceiver;
import cn.edu.zjicm.wordsnet_d.BroadcastReceiver.ScreenBroadcastReceiver;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.data.DataManager;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.data.test.Question;
import cn.edu.zjicm.wordsnet_d.data.test.TestActivityInterface;
import cn.edu.zjicm.wordsnet_d.data.test.TestManager;
import cn.edu.zjicm.wordsnet_d.data.test.TestManagerNormalMode;
import cn.edu.zjicm.wordsnet_d.data.test.TestManagerSprintMode;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.download.DownloadManager;
import cn.edu.zjicm.wordsnet_d.fragment.ExamRunMode10Fragment;
import cn.edu.zjicm.wordsnet_d.fragment.ExamRunMode1Fragment;
import cn.edu.zjicm.wordsnet_d.fragment.ExamRunMode2Fragment;
import cn.edu.zjicm.wordsnet_d.fragment.ExamRunMode34Fragment;
import cn.edu.zjicm.wordsnet_d.fragment.ExamRunMode56Fragment;
import cn.edu.zjicm.wordsnet_d.fragment.PunchOutFragment;
import cn.edu.zjicm.wordsnet_d.fragment.RestFragment;
import cn.edu.zjicm.wordsnet_d.synchronize.ExpInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.DateTimeUtils;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.NightModeUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;
import cn.edu.zjicm.wordsnet_d.view.MyDialog;
import cn.edu.zjicm.wordsnet_d.view.WriteView;

import com.umeng.analytics.MobclickAgent;

public class ExamRunActivity extends WordBaseActivity implements Runnable, TestActivityInterface {

	public static final int STUDY_MODE = 0;
	public static final int REVIEW_MODE = 1;

	public static void startActivity(Context context, int familiarDegree, int mode) {
		Intent i = new Intent(context, ExamRunActivity.class);
		i.putExtra("familiar_degree", familiarDegree);
		i.putExtra("mode", mode);
		context.startActivity(i);
		// finish();
	}

	private int mode;
	private int familiarDegree; // 相应的熟悉度
	private long learnTime = 0; // 测试时间
	private int reviewNum = 0; // 复习个数
	private int learnNum = 0; // 新学个数
	private PopupWindow mWriteWindow;
	private WriteView mWriteView;
	public TextView testResultText1Front, testResultText2Front;
	public TextView testResultText1, testResultText2;
	public ProgressBar mProgressBar1, mProgressBar2;
	public TextView expText, todayStudyNewWordCountText, todayReviewWordCountText;

	public TextView writeAgainButton_independent, closeButton_independent;
	private ViewFlipper examFragmentFlipper;

	private LinearLayout mScrollView;

	private View mMask; // 弹出窗口时的遮罩

	private PopupWindow mPopupWindow;
	private View menuView;
	private int screenWidth;
	Display display;

	WordFactory wf = WordFactory.getInstance(this);

	// private List<Question> questions = new LinkedList<Question>();//一组测试题
	private TestManager testManager; // 全部测试题
	private Question rQuestion; // 当前测试题
	private OneWord mOneWord;// 当前单词
	// 错误列表，有待修改
	public static List<OneWord> wrong_list = new Vector<OneWord>();
	public static ExamRunActivity mContext;
	private Date testStartTime;
	DataToRestActivity mDataToRestActivity;

	Handler handler = new Handler();

	ExamRunMode1Fragment mMode1Fragment = null;
	ExamRunMode2Fragment mMode2Fragment = null;
	ExamRunMode34Fragment mMode34Fragment = null;
	ExamRunMode56Fragment mMode56Fragment = null;
	ExamRunMode10Fragment mMode10Fragment = null;
	PunchOutFragment mPunchOutFragment;

	private boolean showRestFlag = false;// 判断是否休息
	private boolean overThisRestTime = false; // 在需要休息的那一分钟（20、40...）,如果点击继续学习，就不要再出需要休息页面
	private boolean showMainActivity = false; // 判断是否返回主页面
	private boolean pauseStudyTimerFlag = false; // 暂停学习的计时
	private boolean clearTimerFlag = false; // 清空学习计时
	private long startTime; // 开始时间
	public static boolean homeFlag = false; // 是否点击了home键
	public static boolean lockScreenFlag = false; // 是否锁屏

	private MyTimerThread myTimerThread;

	private OneWord ow;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设定调整音量为媒体音量
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		setTitleBarStyle(TITLE_BAR_STYLE_BACK_BUTTON);

		// setTitleTextGravityCenter();
		setBackButton(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (!showMainActivity) {
					stopTest();
				} else {
					toFinish();
					if (mDataToRestActivity.isfinish() && !WordFactory.getInstance(mContext).todayHasPunchOut()) {
						LogUtil.d("点击左上角返回键记录时间");
						mRestFragment.recordNotPunchDate();
					}
				}

			}
		});

		setContentView(R.layout.activity_exam_run);

		familiarDegree = this.getIntent().getIntExtra("familiar_degree", 0);
		mode = this.getIntent().getIntExtra("mode", ExamRunActivity.STUDY_MODE);
		if (mode == ExamRunActivity.STUDY_MODE)
			setTitleText("学习");
		else
			setTitleText("复习单词");

		testResultText1Front = (TextView) findViewById(R.id.test_result_text1_front);
		testResultText2Front = (TextView) findViewById(R.id.test_result_text2_front);
		testResultText1 = (TextView) findViewById(R.id.test_result_text1);
		testResultText2 = (TextView) findViewById(R.id.test_result_text2);
		mProgressBar1 = (ProgressBar) findViewById(R.id.progressBar1);
		mProgressBar2 = (ProgressBar) findViewById(R.id.progressBar2);
		expText = (TextView) findViewById(R.id.exp_text);
		todayStudyNewWordCountText = (TextView) findViewById(R.id.today_study_new_word_count_text);
		todayReviewWordCountText = (TextView) findViewById(R.id.today_review_word_count_text);

		mScrollView = (LinearLayout) findViewById(R.id.exam_run_scroll_view);

		examFragmentFlipper = (ViewFlipper) findViewById(R.id.word_exam_mode1_fragment_container_flipper);

		mMask = findViewById(R.id.guide_studing);

		mLayout = (LinearLayout) findViewById(R.id.exam_run_layout);

		mDataToRestActivity = DataToRestActivity.getInstance();

		testStartTime = new Date();
		startTime = System.currentTimeMillis();
		initTestCount();
		displayResult();
		startTest();
		registerMyReceiver();
		mContext = ExamRunActivity.this;
	}

	public static Context getContext() {
		return mContext;
	}

	// 开始计时
	private void startTimer() {
		// 超过5分钟，学习时间清空为0
		if (clearTimerFlag) {
			startTime = System.currentTimeMillis();
			clearTimerFlag = !clearTimerFlag;
		}
		myTimerThread = new MyTimerThread();
		// 过一秒钟开始计时
		handler.postDelayed(myTimerThread, 1000);
	}

	private int mPauseTime = 0;
	private int studySeconds, studyMinutes;

	class MyTimerThread implements Runnable {

		@Override
		public void run() {
			if (!pauseStudyTimerFlag) { // 学习的计时
				// time = getTime(testStartTime);

				learnTime = System.currentTimeMillis() - startTime;
				studySeconds = (int) (learnTime / 1000);
				studyMinutes = studySeconds / 60;
				if (studyMinutes > 0) {
					studySeconds = studySeconds % (studyMinutes * 60);
				}
				if (studyMinutes == 20 || studyMinutes == 40 || studyMinutes == 60 || studyMinutes == 80) {
					// if (studyMinutes == 1 || studyMinutes == 3 ||
					// studyMinutes == 5 || studyMinutes == 7) {
					if (!overThisRestTime) {
						showRestFlag = true;
					}
				} else {
					overThisRestTime = false;
				}
				// LogUtil.d("Tag", "学习中：" + studyMinutes + ":" + studySeconds +
				// ",overThisRestTime=" + overThisRestTime);
			} else { // 点击home键或者锁屏时的计时
				// time = getTime(pauseTime);
				mPauseTime++;
				if (mPauseTime >= 5 * 60) {
					// if (mPauseTime >= 10) {
					clearTimerFlag = true;
					// LogUtil.d("Tag", "暂停时间超过5分钟,clearTimerFlag = " +
					// clearTimerFlag);
				}
				// LogUtil.d("Tag", "暂停中,mPauseTime = " + mPauseTime);
			}
			handler.postDelayed(this, 1000);
		}

	}

	// 暂停当前线程
	public void pauseTimer() {
		handler.removeCallbacks(myTimerThread); // 去掉现有的计时器
		// 点击了home键或者锁屏，暂停学习计时
		if (homeFlag || lockScreenFlag) {
			pauseStudyTimerFlag = true;
		} else {
			pauseStudyTimerFlag = false;
		}
		startTimer();
	}

	@SuppressLint("NewApi")
	private void initMenu(View view) {
		display = getWindowManager().getDefaultDisplay();
		if (android.os.Build.VERSION.SDK_INT >= 13) {
			Point size = new Point();
			display.getSize(size);
			screenWidth = size.x;
		} else {
			screenWidth = display.getWidth();
		}
		LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		menuView = mLayoutInflater.inflate(R.layout.popmenu_exam_run, null);
		mPopupWindow = new PopupWindow(menuView, (int) (screenWidth / 2.0), ViewGroup.LayoutParams.WRAP_CONTENT);
		mPopupWindow.setFocusable(true); // 取得焦点，创建出来的popupWindow默认无焦点
		mPopupWindow.setTouchable(true);
		mPopupWindow.setOutsideTouchable(true);
		ColorDrawable mDrawable = new ColorDrawable(00000000);
		mPopupWindow.setBackgroundDrawable(mDrawable);
		mPopupWindow.update();
		menuView.setFocusableInTouchMode(true);
		menuView.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if ((keyCode == KeyEvent.KEYCODE_MENU) && (mPopupWindow.isShowing())) {
					mPopupWindow.dismiss();// 这里写明模拟menu的PopupWindow退出就行
					return true;
				}
				return false;
			}
		});

		LinearLayout setToFamiliarButton = (LinearLayout) menuView.findViewById(R.id.btn_set_to_familiar);
		LinearLayout setToTooeasyButton = (LinearLayout) menuView.findViewById(R.id.btn_set_to_tooeasy);
		setToFamiliarButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setToFamiliar();
				mPopupWindow.dismiss();
			}
		});
		setToTooeasyButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setToTooEasy();
				mPopupWindow.dismiss();
			}
		});
	}

	void showPopMenu() {

		initMenu(getRightButton1());
		setRightButton1(null, R.drawable.more_button_selector, new OnClickListener() {
			@Override
			public void onClick(View v) {
				mPopupWindow.showAsDropDown(getRightButton1(), -(int) (mPopupWindow.getWidth() - 9.0 * getRightButton1().getWidth() / 10.0), 0);
				if (AppPreference.isFirstShowGuideStuding(ExamRunActivity.this)) {
					hideGuide();
					AppPreference.setFisrtShowGuideStuding(ExamRunActivity.this, false);
				}
			}
		});

		if (Utils.immersionStatusBarForXiaoMi(this)) {
			int paddingLeftRight = (int) (20 * getResources().getDisplayMetrics().density);
			LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
			getRightButton1().setLayoutParams(ll);
			getRightButton1().setPadding(paddingLeftRight, 0, paddingLeftRight, 0);
		}
	}

	private MyDialog mSetToFamiliarConfirmWindow;

	void setToFamiliar() {
		if (AppPreference.isShowSetToFamiliarHint(this)) {
			setWordToFamiliar();
			return;
		}

		View view = View.inflate(this, R.layout.window_set_to_familiar, null);
		if (mSetToFamiliarConfirmWindow == null) {
			Button confirmButton = (Button) view.findViewById(R.id.set_to_familiar_confirm_button);
			Button cancleButton = (Button) view.findViewById(R.id.set_to_familiar_cancle_button);
			TextView hintText1 = (TextView) view.findViewById(R.id.set_to_familiar_Remind1);
			TextView hintText2 = (TextView) view.findViewById(R.id.set_to_familiar_Remind2);
			hintText1.setText(R.string.set_to_familiar_hint1);
			hintText2.setText(R.string.set_to_familiar_hint2);
			final CheckBox showHintCheckBox = (CheckBox) view.findViewById(R.id.set_to_familiar_showhint_checkbox);
			confirmButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mSetToFamiliarConfirmWindow.dismiss();
					mSetToFamiliarConfirmWindow = null;

					setWordToFamiliar();

					AppPreference.setShowSetToFamiliarHint(ExamRunActivity.this, showHintCheckBox.isChecked());
				}
			});
			cancleButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mSetToFamiliarConfirmWindow.dismiss();
					mSetToFamiliarConfirmWindow = null;
				}
			});
			mSetToFamiliarConfirmWindow = new MyDialog(this, view, R.style.mydialog, false);
			mSetToFamiliarConfirmWindow.setCanceledOnTouchOutside(true);
		}
		mSetToFamiliarConfirmWindow.show();
	}

	void setToTooEasy() {
		if (AppPreference.isShowSetToTooEasyHint(this)) {
			setWordToTooEasy();
			return;
		}

		View view = View.inflate(this, R.layout.window_set_to_familiar, null);
		if (mSetToFamiliarConfirmWindow == null) {
			// init PopWindow cotentview
			TextView confirmButton = (TextView) view.findViewById(R.id.set_to_familiar_confirm_button);
			TextView cancleButton = (TextView) view.findViewById(R.id.set_to_familiar_cancle_button);
			TextView hintText1 = (TextView) view.findViewById(R.id.set_to_familiar_Remind1);
			TextView hintText2 = (TextView) view.findViewById(R.id.set_to_familiar_Remind2);

			hintText1.setText(R.string.set_to_tooeasy_hint1);
			hintText2.setText(R.string.set_to_tooeasy_hint2);
			final CheckBox showHintCheckBox = (CheckBox) view.findViewById(R.id.set_to_familiar_showhint_checkbox);
			confirmButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mSetToFamiliarConfirmWindow.dismiss();
					mSetToFamiliarConfirmWindow = null;

					setWordToTooEasy();

					AppPreference.setShowSetToTooEasyHint(ExamRunActivity.this, showHintCheckBox.isChecked());
				}
			});
			cancleButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mSetToFamiliarConfirmWindow.dismiss();
					mSetToFamiliarConfirmWindow = null;
				}
			});

			mSetToFamiliarConfirmWindow = new MyDialog(this, view, R.style.mydialog, false);
			mSetToFamiliarConfirmWindow.setCanceledOnTouchOutside(true);
		}
		mSetToFamiliarConfirmWindow.show();
	}

	void setWordToFamiliar() {
		OneWord mOneWord = rQuestion.getWord();
		OneWord w = DataManager.getInstance().findWord(mOneWord, ExamRunActivity.this);
		DataManager.getInstance().changeUnFamiliarToFamiliar(w, ExamRunActivity.this);
		// if(w!=null)
		// mOneWord = w;

		Toast.makeText(ExamRunActivity.this, mOneWord.getLemma() + "已设为熟词", Toast.LENGTH_SHORT).show();
		removeCurWord();
	}

	void setWordToTooEasy() {
		OneWord mOneWord = rQuestion.getWord();
		OneWord w = DataManager.getInstance().findWord(mOneWord, ExamRunActivity.this);
		DataManager.getInstance().changeUnFamiliarToTooEasy(w, ExamRunActivity.this);
		// if(w!=null)
		// mOneWord = w;

		Toast.makeText(ExamRunActivity.this, mOneWord.getLemma() + "已设为太简单", Toast.LENGTH_SHORT).show();
		removeCurWord();
	}

	void startTest() {
		if (AppPreference.isOpenSprintMode(this))
			testManager = new TestManagerSprintMode(familiarDegree, mode, this);
		else
			testManager = new TestManagerNormalMode(familiarDegree, mode, this);
		AppPreference.setLastTestStartTime(this, DateTimeUtils.getTimeOfMinuteWithZoneRawOffsetTime());
		wrong_list.clear();
		nextQuestion();

	}

	Handler syncHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case UserInterface.MSG_START:
				// dialog2 = ProgressDialog.show(context, null, "正在同步用户数据...");
				break;
			case UserInterface.MSG_SUCCESS:
				// Toast.makeText(ExamRunActivity.this, "学习完同步用户数据成功",
				// Toast.LENGTH_SHORT).show();
				// 修改自动同步日期
				AppPreference.setAutoSyncDateAfterStudy(ExamRunActivity.this, DateTimeUtils.getDate());
				break;
			case UserInterface.MSG_UNSUCCESS:
				// Toast.makeText(ExamRunActivity.this, "同步失败",
				// Toast.LENGTH_SHORT)
				// .show();
				break;
			case UserInterface.MSG_BAD_NETWORK:
				// Toast.makeText(ExamRunActivity.this, "同步失败,请确认网络是否连接",
				// Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				// Toast.makeText(ExamRunActivity.this, "同步失败,无法访问网站，请确认网络是否连接",
				// Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};

	// 每天第一次完成学习，同步用户数据
	protected void toSync(Context context) {
		int today = DateTimeUtils.getDate();
		int autoSyncDateAfterStudy = AppPreference.getAutoSyncDateAfterStudy(context);

		if (UserInterface.getInstance(ExamRunActivity.this).isLogin() && autoSyncDateAfterStudy != today) {
			syncHandler.sendMessage(syncHandler.obtainMessage(UserInterface.MSG_START));
			UserInterface.getInstance(context).sync(syncHandler);
		}
	}

	// 结束测试
	private void stopTest() {
		// 更新notification
		// AlarmReceiver.alarmUpdateStudy(this);
		intoRestFragment();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean consumed = false;
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if (!showMainActivity) {
				stopTest();
			} else {
				toFinish();
				if (mDataToRestActivity.isfinish() && !WordFactory.getInstance(mContext).todayHasPunchOut()) {
					LogUtil.d("点击右下角返回键记录时间");
					mRestFragment.recordNotPunchDate();
				}
			}

		}
		return consumed;
	}

	public void showDownloadVoiceWindow(Handler handler) {
		DownloadManager downloadManager = new DownloadManager(this, handler, true, rQuestion.getWord());
		downloadManager.showAskDownloadWindow();
	}

	public void displayWriteView() {
		TypedValue typedValue = new TypedValue();
		getTheme().resolveAttribute(R.attr.spell_dialog_bg_blur, typedValue, true);
		mMask.setBackgroundResource(typedValue.resourceId);
		mMask.setVisibility(View.VISIBLE);
		mMask.scrollTo(0, mScrollView.getScrollY());
		hideTitle();
	}

	ImageView playVoice = null;

	public void showWriteWindow() {
		if (mWriteWindow == null) {
			// init PopWindow cotentview
			View view = View.inflate(this, R.layout.window_write, null);
			ImageView writeAgainButton = (ImageView) view.findViewById(R.id.write_again_button);
			ImageView hintButton = (ImageView) view.findViewById(R.id.hint);
			ImageView closeButton = (ImageView) view.findViewById(R.id.write_close_button);
			playVoice = (ImageView) view.findViewById(R.id.play_voice_writeview);
			mWriteView = (WriteView) view.findViewById(R.id.write_view);

			writeAgainButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mWriteView.reWrite();
				}
			});
			closeButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mWriteWindow.dismiss();
				}
			});
			hintButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Toast.makeText(ExamRunActivity.this, mWriteView.hint(), Toast.LENGTH_SHORT).show();
				}
			});
			playVoice.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mWriteView.playOneWordVoice();
				}
			});
			mWriteWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			mWriteWindow.setFocusable(true);
			mWriteWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.transparent_bg_drawable));
			mWriteWindow.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss() {
					displayDetailView();
					showTitle();
				}
			});
		}

		if (playVoice != null) {
			if (NightModeUtil.isNightModeNow()) {
				if (FileManager.isVoiceFileExist(mContext, rQuestion.getWord())) {
					playVoice.setImageResource(R.drawable.write_view_play_voice_ico_night_selector);
				} else {
					playVoice.setImageResource(R.drawable.write_view_play_ico_unclickable_night);
				}
			} else {
				if (FileManager.isVoiceFileExist(mContext, rQuestion.getWord())) {
					playVoice.setImageResource(R.drawable.write_view_play_voice_ico_selector);
				} else {
					playVoice.setImageResource(R.drawable.write_view_play_ico_unclickable);
				}
			}
		}
		// mWriteView.init(rQuestion.getLemma(), rQuestion.getCn(),
		// rQuestion.getPhonetic());
		mWriteView.init(rQuestion.getWord());
		mWriteView.reWrite();
		if (mWriteView.isToShowKeyBoard()) {
			mWriteWindow.showAtLocation(mMask, Gravity.TOP, 0, 0);
		} else
			mWriteWindow.showAtLocation(mMask, Gravity.CENTER, 0, 0);
	}

	public void displayDetailView() {
		mMask.setVisibility(View.GONE);
	}

	public void next(boolean result) {
		if (rQuestion == null)
			return;
		if (result)
			testManager.rightAnswer(rQuestion);
		else
			testManager.wrongAnswer(rQuestion);
		rQuestion = null;
		handler.post(ExamRunActivity.this);
		// handler.postDelayed(ExamRunActivity.this, TEST_INTERVAL);
		// nextQuestion();
	}

	public void removeCurWord() {
		// TODO Auto-generated method stub
		if (rQuestion == null)
			return;
		testManager.removeFromQuestionList(rQuestion);
		rQuestion = null;
		handler.post(ExamRunActivity.this);
		// handler.postDelayed(ExamRunActivity.this, TEST_INTERVAL);
		// nextQuestion();
	}

	private void nextQuestion() {
		handler.removeCallbacks(this);

		rQuestion = testManager.nextQuestion();
		if (rQuestion != null) {
			if (!showRestFlag) { // 不需要休息
				mode1();
				// showPunchOutFragment();
			} else {
				stopTest(); // 需要休息
			}
		} else {
			handler.removeCallbacks(myTimerThread); // 完成学习时停止计时
			stopTest();
		}
	}

	public static final int TEST_INTERVAL = 0;

	@Override
	public void run() {
		// TODO Auto-generated method stub
		this.nextQuestion();
	}

	private int testMode = -1;

	// 进入休息页面
	private void intoRestFragment() {

		mLayout.setVisibility(View.GONE);
		RelativeLayout.LayoutParams fl = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		mScrollView.setLayoutParams(fl);

		getData();
		toSync(this);
		if (expChange != 0 || AppPreference.getEXPUpdated(this) == false) {
			AppPreference.setEXPUpdated(this, false);
			ExpInterface.getInstance(this).setExp();
		}
		if (testMode == 1 || testMode == 2) {
			hideRightButton0();
		}
		if (testMode == 2) {
			hideRightButton1();
			hideGuide();
		}
		if (mRestFragment == null) {
			mRestFragment = new RestFragment(mode);
			FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
			ft.add(R.id.rest_fragment_container, mRestFragment);
			ft.commit();
		} else {
			mRestFragment.initView();
		}
		examFragmentFlipper.setInAnimation(ExamRunActivity.this, R.anim.open_enter);
		// examFragmentFlipper.setOutAnimation(ExamRunActivity.this,
		// R.anim.close_exit);
		examFragmentFlipper.setDisplayedChild(5);

		mLayout.setVisibility(View.GONE);
		showMainActivity = true;
	}

	public void showPunchOutFragment() {
		// mLayout.setVisibility(View.GONE);
		// FrameLayout.LayoutParams fl = new
		// FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
		// LayoutParams.MATCH_PARENT);
		// mScrollView.setLayoutParams(fl);

		setTitleText("打卡完成");
		mPunchOutFragment = new PunchOutFragment();
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		ft.add(R.id.punch_out_fragment_container, mPunchOutFragment);
		ft.commit();
		examFragmentFlipper.setDisplayedChild(6);
	}

	public void mode1() {

		testMode = testManager.getModeNo();

		// 模式1,2，显示难词按钮，否则隐藏
		if (testMode == 1 || testMode == 2) {
			mOneWord = rQuestion.getWord();
			setRightButton0(mOneWord.isDifficulty(), onClick);
			// showGuide();
		} else {
			hideRightButton0();
			// hideGuide();
		}

		// 模式2，显示弹出式按钮菜单，否则隐藏
		if (testMode == 2) {
			showPopMenu();
			showGuide();
		} else {
			hideRightButton1();
			hideGuide();
		}
		if (testMode == 1) {
			if (mMode1Fragment == null) {
				mMode1Fragment = new ExamRunMode1Fragment(rQuestion.getWord(), this);
				FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
				ft.add(R.id.word_exam_mode1_fragment_container, mMode1Fragment);
				ft.commit();
			} else
				mMode1Fragment.initViewForNewWord(rQuestion.getWord());
			examFragmentFlipper.setDisplayedChild(0);
		} else if (testMode == 2) {
			if (mMode2Fragment == null) {
				mMode2Fragment = new ExamRunMode2Fragment(rQuestion.getWord(), this);
				FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
				ft.add(R.id.word_exam_mode2_fragment_container, mMode2Fragment);
				ft.commit();
			} else
				mMode2Fragment.initViewForNewWord(rQuestion.getWord());
			examFragmentFlipper.setDisplayedChild(1);
		} else if (testMode == 3 || testMode == 4) {
			if (mMode34Fragment == null) {
				mMode34Fragment = new ExamRunMode34Fragment(rQuestion.getRelationShip(), testMode, this);
				FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
				ft.add(R.id.word_exam_mode34_fragment_container, mMode34Fragment);
				ft.commit();
			} else
				mMode34Fragment.initViewForNewRelationShip(rQuestion.getRelationShip(), testMode);
			examFragmentFlipper.setDisplayedChild(2);
		} else if (testMode == 5 || testMode == 6) {
			if (mMode56Fragment == null) {
				mMode56Fragment = new ExamRunMode56Fragment(rQuestion.getRelationShip(), testMode, this);
				FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
				ft.add(R.id.word_exam_mode56_fragment_container, mMode56Fragment);
				ft.commit();
			} else
				mMode56Fragment.initViewForNewRelationShip(rQuestion.getRelationShip(), testMode);
			examFragmentFlipper.setDisplayedChild(3);
		} else if (testMode == 10) {
			if (mMode10Fragment == null) {
				mMode10Fragment = new ExamRunMode10Fragment(rQuestion.getWord(), this);
				FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
				ft.add(R.id.word_exam_mode10_fragment_container, mMode10Fragment);
				ft.commit();
			} else
				mMode10Fragment.initViewForNewRelationShip(rQuestion.getWord());
			examFragmentFlipper.setDisplayedChild(4);
		} else
			next(true);
	}

	int newWordNumber, reviewWordNumber, newWordCount, reviewWordCount;
	int newRelationShipNumber, reviewRelationShipNumber, newRelationShipCount, reviewRelationShipCount;
	int expChange = 0; // 经验值变化值

	private RestFragment mRestFragment;
	private LinearLayout mLayout;
	private HomeKeyEventBroadCastReceiver homeKeyReceiver;
	private ScreenBroadcastReceiver screenBroadcastReceiver;

	void initTestCount() {
		if (familiarDegree == OneWord.DEGREE_UNFAMILIAR) {
			newWordNumber = wf.getNumberOfWordListNotStudyOfDegree(familiarDegree);

			// long time11,time21;
			// time11 = System.currentTimeMillis();
			if (mode == ExamRunActivity.STUDY_MODE)
				reviewWordNumber = wf.getNumberOfWordsForTestOfDegree(familiarDegree) - newWordNumber;
			else
				reviewWordNumber = wf.getRealNumberOfWordsForTestOfDegree(familiarDegree) - newWordNumber;
			// time21 = System.currentTimeMillis();
			// Log.e("exam count", time21 - time11 + ":" + (newWordNumber +
			// reviewWordNumber));

			newWordCount = newWordNumber;
			reviewWordCount = reviewWordNumber;
		}
		// else {
		// newRelationShipNumber =
		// wf.getNumberOfRelationShipsNotStudyOfDegree(familiarDegree);
		// reviewRelationShipNumber =
		// wf.getNumberOfRelationShipsForTestOfDegree(familiarDegree)
		// - newRelationShipNumber;
		// newRelationShipCount = 0;
		// reviewRelationShipCount = reviewRelationShipNumber;
		// }
	}

	private void getData() {
		mDataToRestActivity.setFamiliarDegree(familiarDegree);

		mDataToRestActivity.setLearnTime(learnTime);
		if (familiarDegree == OneWord.DEGREE_UNFAMILIAR) {
			reviewNum = reviewWordNumber - reviewWordCount;
			learnNum = newWordNumber - newWordCount;
		} else if (familiarDegree == OneWord.DEGREE_FAMILIAR) {
			reviewNum = reviewRelationShipNumber - reviewRelationShipCount;
			learnNum = newRelationShipCount;
		}

		mDataToRestActivity.setIstrue(true);
		mDataToRestActivity.setReviewNum(reviewNum);
		mDataToRestActivity.setLearnNum(learnNum);
		mDataToRestActivity.setIsfinish(reviewWordCount == 0 && newWordCount == 0);
		mDataToRestActivity.setDBChanged(true);
		mDataToRestActivity.setExpChange(expChange);
	}

	/*
	 * private int getTime(Date time) { return (int) (new Date().getTime() -
	 * time.getTime()) / (1000 * 60); }
	 */

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("menu");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if ((mPopupWindow != null) && (testManager.getModeNo() == 2)) {
			if (!mPopupWindow.isShowing()) {
				mPopupWindow.showAsDropDown(getRightButton1(), -(int) (mPopupWindow.getWidth() - 9.0 * getRightButton1().getWidth() / 10.0), 0);
			} else {
				mPopupWindow.dismiss();
			}
		}
		return false;
	}

	void displayResult() {
		expText.setText(expChange + "");
		todayStudyNewWordCountText.setText(AppPreference.getTodayStudyNewWordCount(this) + "");
		todayReviewWordCountText.setText(AppPreference.getTodayReviewWordCount(this) + "");

		// double rate = 1.0*rightCount/testCount;
		// testResultText.setText("已测试"+ testCount +"个搭配，记得" + rightCount
		// +"个，正确率" +
		// ((int) (rate * 1000))/10.0 + "%");
		if (familiarDegree == OneWord.DEGREE_UNFAMILIAR) {
			// testResultText1Front.setText("新学单词 " + newWordCount + "/"
			// + newWordNumber
			// + "，复习单词" + reviewWordCount + "/"
			// + reviewWordNumber);
			testResultText1Front.setText("新学单词");
			testResultText2Front.setText("复习单词");
			int a = newWordNumber - newWordCount;
			if (a < 0)
				a = 0;
			int b = newWordNumber;
			if (b < 0)
				b = 0;
			int c = reviewWordNumber - reviewWordCount;
			if (c < 0)
				c = 0;
			int d = reviewWordNumber;
			if (d < 0)
				d = 0;
			testResultText1.setText(a + "/" + b);
			testResultText2.setText(c + "/" + d);

			if (b == 0)
				mProgressBar1.setProgress(100);
			else
				mProgressBar1.setProgress(100 * a / b);
			if (d == 0)
				mProgressBar2.setProgress(100);
			else
				mProgressBar2.setProgress(100 * c / d);

		} else if (familiarDegree == OneWord.DEGREE_FAMILIAR) {
			// testResultText1Front.setText("复习搭配"+ reviewRelationShipCount +
			// "/"
			// + reviewRelationShipNumber
			// + "，新学搭配" + newRelationShipCount);
			testResultText1Front.setText("新学搭配");
			testResultText2Front.setText("复习搭配");
			testResultText1.setText(newRelationShipCount);
			testResultText2.setText((reviewRelationShipNumber - reviewRelationShipCount) + "/" + reviewRelationShipNumber);
			mProgressBar1.setProgress(50);
			if (reviewRelationShipNumber == 0)
				mProgressBar2.setProgress(100);
			else
				mProgressBar2.setProgress(100 * (reviewRelationShipNumber - reviewRelationShipCount) / reviewRelationShipNumber);

			// 新学搭配中只找到一个数值(没找到分子分母),这里的mProgressBar1就设置为一半50%；
		}
	}

	public void updateResult(int updateExpValue) {
		// 更新新学单词和复习单词数
		if (rQuestion.getOldDegree() < 20) {
			newWordCount--;
			AppPreference.setTodayStudyNewWordCount(this, AppPreference.getTodayStudyNewWordCount(this) + 1);
		} else {
			reviewWordCount--;
			AppPreference.setTodayReviewWordCount(this, AppPreference.getTodayReviewWordCount(this) + 1);
		}
		/*
		 * if(rQuestion.getFamiliarDegree() == 0) newRelationShipCount++; else
		 * reviewRelationShipCount--;
		 */

		expChange += updateExpValue; // 更新经验值变化值
		AppPreference.setEXP(this, AppPreference.getEXP(this) + updateExpValue); // 更新经验值
		// Toast.makeText(this, "经验值变化" + updateExpValue,
		// Toast.LENGTH_SHORT).show();

		displayResult(); // 更新进度条数据
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this);
		homeFlag = false;
		lockScreenFlag = false;
		// 如果不为空，则说明已经启动了一个计时线程
		if (myTimerThread != null) {
			// mStudyTime = mStudyTime-mPauseTime;
			mPauseTime = 0;
			pauseTimer();
		} else {
			startTimer();
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		unRegisterMyReceiver();
		super.onDestroy();
	}

	// 点击继续学习
	public void continueStudy() {
		examFragmentFlipper.setOutAnimation(ExamRunActivity.this, R.anim.close_exit);

		examFragmentFlipper.setInAnimation(null);
		examFragmentFlipper.setOutAnimation(null);
		showRestFlag = false;
		showMainActivity = false;
		overThisRestTime = true;
		mLayout.setVisibility(View.VISIBLE);
		// mode1();
		nextQuestion(); // 调用这个方法，可以对rQuestion是否为空进行判断
	}

	public void toFinish() {
		handler.removeCallbacks(myTimerThread);
		unRegisterMyReceiver();
		finish();
	}

	private void registerMyReceiver() {
		// 注册home键监听器
		homeKeyReceiver = new HomeKeyEventBroadCastReceiver();
		IntentFilter filter1 = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		registerReceiver(homeKeyReceiver, filter1);

		screenBroadcastReceiver = new ScreenBroadcastReceiver();
		filter1 = new IntentFilter();
		filter1.addAction(Intent.ACTION_SCREEN_OFF);
		filter1.addAction(Intent.ACTION_SCREEN_ON);
		registerReceiver(screenBroadcastReceiver, filter1);
	}

	private void unRegisterMyReceiver() {
		if (homeKeyReceiver != null) {
			unregisterReceiver(homeKeyReceiver);
			homeKeyReceiver = null;
		}
		if (screenBroadcastReceiver != null) {
			unregisterReceiver(screenBroadcastReceiver);
			screenBroadcastReceiver = null;
		}
	}

	private void showGuide() {
		if (AppPreference.isFirstShowGuideStuding(ExamRunActivity.this)) {
			// ImageView guideStuding = (ImageView)
			// findViewById(R.id.guide_studing);
			showGuideForAffix();
			mMask.setBackgroundResource(R.drawable.guide_in_studing);
			mMask.setVisibility(View.VISIBLE);
			mMask.setFocusable(true);
			mMask.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					hideGuide();
					AppPreference.setFisrtShowGuideStuding(ExamRunActivity.this, false);
				}
			});

		} else
			hideGuide();
	}

	private void hideGuide() {
		mMask.setVisibility(View.GONE);
		removeGuideForAffix();
	}

	@Override
	public void next(ANSWER_RESULT result) {
		if (rQuestion == null)
			return;
		if (result == TestActivityInterface.ANSWER_RESULT.RIGHT)
			testManager.rightAnswer(rQuestion);
		else
			testManager.wrongAnswer(rQuestion);
		rQuestion = null;
		handler.post(ExamRunActivity.this);
		// handler.postDelayed(ExamRunActivity.this, TEST_INTERVAL);
		// nextQuestion();
	}

	/**
	 * 标记难词的按钮监听
	 * 
	 * @since2015.05.27
	 */
	public OnClickListener onClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (mOneWord.isDifficulty()) {
				mOneWord.setDifficulty(false, ExamRunActivity.this);
				Toast.makeText(ExamRunActivity.this, R.string.set_to_difficult_hint2, Toast.LENGTH_SHORT).show();
			} else {
				mOneWord.setDifficulty(true, ExamRunActivity.this);
				Toast.makeText(ExamRunActivity.this, R.string.set_to_difficult_hint1, Toast.LENGTH_SHORT).show();
			}
			ExamRunActivity.this.setRightButton0(mOneWord.isDifficulty());
		}
	};

}
